package com.itheima.edu.info.manager.controller;

import com.itheima.edu.info.manager.domain.Teacher;
import com.itheima.edu.info.manager.service.TeacherService;

import java.util.Scanner;

public abstract class BaseTeacherController {
    private Scanner sc = new Scanner(System.in);
    private TeacherService service = new TeacherService();

    public final void start() {
        while (true) {
            System.out.println("--------欢迎来到 <老师> 管理系统--------");
            System.out.println("请输入您的选择: 1.添加老师  2.删除老师  3.修改老师  4.查看老师  5.退出");
            String choice = sc.next();
            switch (choice) {
                case "1":
                    addTeacher();
                    break;
                case "2":
                    deleteTeacherById();
                    break;
                case "3":
                    updateTeacher();
                    break;
                case "4":
                    findAllTeacher();
                    break;
                case "5":
                    System.out.println("感谢您使用老师管理系统,再见!");
                    return;
                default:
                    System.out.println("您的输入有误,请重新输入");
                    break;
            }
        }
    }

    public final void updateTeacher() {
        System.out.println("请输入要修改的老师工号:");
        String updateId = inputTeachId(true);
        Teacher newtea = inputTeacherInfo(updateId);
        service.updateTeacher(updateId, newtea);
        System.out.println("修改成功!");
    }

    public final void deleteTeacherById() {
        System.out.println("请输入要删除的老师工号:");
        String delId = inputTeachId(true);
        service.deleteTeacherById(delId);
        System.out.println("删除成功!");
    }

    public final void findAllTeacher() {
        Teacher[] tea = service.findAllTeacher();
        if (tea == null) {
            System.out.println("查无信息,请添加后再试");
            return;
        }
        System.out.println("工号\t\t姓名\t年龄\t生日");
        for (int i = 0; i < tea.length; i++) {
            Teacher t = tea[i];
            if (t != null) {
                System.out.println(t.getId() + "\t" + t.getName() + "\t" + t.getAge() + "\t\t" + t.getBirthday());
            }
        }
    }

    public final void addTeacher() {
        System.out.println("请输入老师工号:");
        String id = inputTeachId(false);
        Teacher tea = inputTeacherInfo(id);
        boolean res = service.addTeacher(tea);
        if (res) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    }

    public abstract Teacher inputTeacherInfo(String id);

    public final String inputTeachId(boolean exit) {
        String id;
        while (true) {
            id = sc.next();
            boolean exists = service.isExists(id);
            if (exists == exit) {
                break;
            } else {
                System.out.println("您输入的工号不可用,请重新输入:");
            }
        }
        return id;
    }
}

